package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.SetmealDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealMapper;

    //分页查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        //使用分页查询插件
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //分页查询数据库
        Page<Setmeal> page = setmealMapper.page(queryPageBean.getQueryString());
        //封装分页数据
        return new PageResult(page.getTotal(), page.getResult());
    }

    //新增套餐
    @Override
    @Transactional
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //像套餐里增加数据
        setmealMapper.insert(setmeal);
        //获取新增套餐的id
        Integer setId = setmeal.getId();
        //获取回显的检查组的id
        setmealMapper.insertBatch(setId, checkgroupIds);
    }

    //删除套餐
    @Transactional
    @Override
    public void delete(Integer id) {
        //删除套餐
        setmealMapper.delete(id);
        //删除关联表中关于套餐的数据
        setmealMapper.deleteById(id);
    }

    //回显套餐
    @Override
    public Setmeal getById(Integer id) {
        Setmeal setmeal = setmealMapper.findById(id);
        return setmeal;
    }

    //修改套餐
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //修改套餐基本信息
        setmealMapper.updateById(setmeal);

        //删除原有检查组数据
        List<Integer> setmealIds = Arrays.asList(setmeal.getId());
        for (Integer id : setmealIds) {
            setmealMapper.deleteBySetId(id);
        }

        //重新插入检查项
        setmealMapper.insertBatch(setmeal.getId(), checkgroupIds);
    }
}
